/**
 * 0. Project	: com.dnbns.bodywater 프로젝트
 *
 * 1. FileName	: AlarmActivity.java
 * 2. Package	: com.dnbns.bodywater
 * 3. 작성자		: 윤화현
 * 4. 작성일		: 2013. 12. 31. 오전 10:00:41
 * 5. Comment	: 
 */

package com.dnbns.bodywater;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;

import com.dnbns.bodywater.adapter.AlarmAdapter;
import com.dnbns.bodywater.bean.AlarmBean;
import com.dnbns.common.AlarmSchedule;
import com.dnbns.common.StaticValue;
import com.dnbns.lib.CodeUtil;

public class AlarmActivity extends FragmentActivity implements WeightDialogFragment.NoticeDialogListener {
	
	private Calendar cal;
	private ArrayList<AlarmBean> mList;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_alarm);
		
		init();
		initTop();
	}

/**
 ***************************************************************
 * init
 ***************************************************************
 */
	
	private void init(){
		cal = Calendar.getInstance();

		ListView list = (ListView)findViewById(R.id.alarm_list);
		
		list.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> adapter, View view, int position, long arg3) {
				// TODO Auto-generated method stub
				WeightDialogFragment dpf = new WeightDialogFragment(
						StaticValue.DIALOG_TIME,
						mList.get(position).getIdx(),
						Integer.valueOf(mList.get(position).getHour()),
						Integer.valueOf(mList.get(position).getMinute()));
				dpf.show(getSupportFragmentManager(), "");
			}
		});
		
		Button alarm_add = (Button)findViewById(R.id.alarm_add);

		alarm_add.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				WeightDialogFragment dpf = new WeightDialogFragment(
						StaticValue.DIALOG_TIME,
						0,
						cal.get(Calendar.HOUR_OF_DAY),
						cal.get(Calendar.MINUTE));
				dpf.show(getSupportFragmentManager(), "");
			}
		});
		
		getDBWater();
	}
	
	private void initTop(){
		ImageView back = (ImageView)findViewById(R.id.back);
		ImageView refresh = (ImageView)findViewById(R.id.refresh);
		back.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});
		refresh.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				AlertDialog.Builder ab = new AlertDialog.Builder(AlarmActivity.this);
				ab.setTitle("초기화");
				ab.setMessage("기본 셋팅으로 바꾸시겠습니까?");
				ab.setPositiveButton("확인", new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						CodeUtil.getInstance(getApplicationContext()).getAssetDB();
						getDBWater();
						dialog.dismiss();
					}
				});
				ab.setNegativeButton("취소", new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						dialog.dismiss();
					}
				});
				ab.show();
			}
		});
	}

/**
 ***************************************************************
 * 메소드
 ***************************************************************
 */
	
    //DB에서 데이터 select.
    private void getDBWater(){
		JSONArray objA = CodeUtil.getInstance(getApplicationContext()).getQuery("alarm");
		mList = new ArrayList<AlarmBean>();
		
		for(int i=0; i<objA.length(); i++){
			try {
				AlarmBean mBean = new AlarmBean();
				mBean.setIdx(objA.getJSONObject(i).getInt("idx"));
				mBean.setHour(objA.getJSONObject(i).getString("hour"));
				mBean.setMinute(objA.getJSONObject(i).getString("minute"));
				mList.add(mBean);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		ListCollections();
		
		AlarmAdapter mAdapter = new AlarmAdapter(this, mList);
		ListView list = (ListView)findViewById(R.id.alarm_list);
		list.setAdapter(mAdapter);
		mAdapter.notifyDataSetInvalidated();
		
		objA = null;
    }
    
    //정렬
	private void ListCollections() {
		Collections.sort(mList, new NameAscCompare());
	}
	
    static class NameAscCompare implements Comparator<AlarmBean> {

		@Override
		public int compare(AlarmBean lhs, AlarmBean rhs) {
			// TODO Auto-generated method stub
			Calendar cal1 = Calendar.getInstance();
			cal1.set(Calendar.HOUR_OF_DAY, Integer.valueOf(lhs.getHour()));
			cal1.set(Calendar.MINUTE, Integer.valueOf(lhs.getMinute()));

			Calendar cal2 = Calendar.getInstance();
			cal2.set(Calendar.HOUR_OF_DAY, Integer.valueOf(rhs.getHour()));
			cal2.set(Calendar.MINUTE, Integer.valueOf(rhs.getMinute()));
			
			return cal1.getTimeInMillis() < cal2.getTimeInMillis() ? -1 : cal1.getTimeInMillis() > cal2.getTimeInMillis() ? 1:0;
		}
    }
    
/**
 ***************************************************************
 * Event
 ***************************************************************
 */

	@Override
	public void onDialogNegativeClick(DialogFragment dialog) {
		// TODO Auto-generated method stub
		dialog.dismiss();
	}

	@Override
	public void onDialogTimeClick(DialogFragment dialog, int idx, String hour, String minute) {
		// TODO Auto-generated method stub
		//추가일 경우.
		if(idx == 0){
			JSONArray jsonA = new JSONArray();
			JSONObject jsonO = new JSONObject();
			try {
				jsonO.put("hour", 		hour);
				jsonO.put("minute", 	CodeUtil.addZero(Integer.valueOf(minute)));
				
				jsonA.put(jsonO);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			try {
				CodeUtil.getInstance(getApplicationContext()).insertAllCode2(jsonA, 2000);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			onAlarm(hour, CodeUtil.addZero(Integer.valueOf(minute)));
		}
		//수정일 경우.
		else{
			JSONArray jsonA = new JSONArray();
			JSONObject jsonO = new JSONObject();
			try {
				jsonO.put("hour", 		hour);
				jsonO.put("minute", 	CodeUtil.addZero(Integer.valueOf(minute)));
				
				jsonA.put(jsonO);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			try {
				CodeUtil.getInstance(getApplicationContext()).updateAllCode2(jsonA, 2000, idx+"");
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			onAlarm(idx);
		}
		getDBWater();
		dialog.dismiss();
	}
	
	//알람 등록
	private void onAlarm(String hour, String minute){
		JSONArray objA = CodeUtil.getInstance(getApplicationContext()).getQuery("alarm2", hour, minute);

		//등록된 것들 해제.
		try {
			AlarmSchedule.getInstance(getApplicationContext()).setAlarmSchedule(
					objA.getJSONObject(0).getInt("idx"),
					objA.getJSONObject(0).getInt("hour"),
					objA.getJSONObject(0).getInt("minute"));
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	//알람 등록
	private void onAlarm(int idx){
		JSONArray objA = CodeUtil.getInstance(getApplicationContext()).getQuery("alarm3", ""+idx);

		//등록된 것들 해제.
		try {
			AlarmSchedule.getInstance(getApplicationContext()).deleteAlarmSchedule(idx);
			
			AlarmSchedule.getInstance(getApplicationContext()).setAlarmSchedule(
					objA.getJSONObject(0).getInt("idx"),
					objA.getJSONObject(0).getInt("hour"),
					objA.getJSONObject(0).getInt("minute"));
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
